# coding=utf-8

import threading
from conf import constant
from views.view_base import *
from common.middlewares import *
from controller.task_controller import TaskController


class TaskView(ViewBase):
    def __init__(self):
        super(TaskView, self).__init__()

    def __is_int_array(self, array):
        array_type = type(array)
        if array_type != list and array_type != tuple:
            return False
        for item in array:
            if type(item) != int:
                return False
        return True

    @dispatch('/get', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(id='int')
    def get(self):
        try:
            task_id = int(self.params.get('id'))
            controller = TaskController()
            data = controller.get(task_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg='查询成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/get_task_contents', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(id='int', page_index='int', page_size='int')
    def get_task_contents(self):
        try:
            task_id = int(self.params.get('id'))
            page_index = int(self.params.get('page_index'))
            page_size = int(self.params.get('page_size'))
            geo_layers = self.params.get('geo_layers', None)
            audit_status = self.params.get('audit_status', None)
            is_modify = self.params.get('is_modify', None)
            controller = TaskController()
            if geo_layers:
                controller.check_geo_layers(geo_layers)
            res, data = controller.get_task_contents(task_id, page_index, page_size, geo_layers,
                                                     audit_status, is_modify)
            if res:
                return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg='查询成功')
            else:
                msg = data
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg=msg)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/get_real', methods=['POST'])
    @authenticated()
    def get_real(self):
        try:
            params = request.get_json()
            controller = TaskController()
            conditions = params.get('conditions')
            for param in conditions:
                if type(param.get('sub_set_id')) != int:
                    return self._render.render_json(
                        code=RESPONSE_PARAMS_ERROR, data={},
                        msg='param.sub_set_id is int')
                controller.check_geo_layers(param.get('geo_layers'))
            x_min = self.params.get('x_min')
            x_max = self.params.get('x_max')
            y_min = self.params.get('y_min')
            y_max = self.params.get('y_max')
            array = controller.get_real(conditions, x_min, y_min, x_max, y_max)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=array, msg='查询成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/get_statistics', methods=['GET', 'POST'])
    @verify_params(id='int')
    @authenticated()
    def get_statistics(self):
        try:
            task_id = int(self.params.get('id'))
            controller = TaskController()
            data = controller.get_statistics(task_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg='查询成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/add_to_submit_list', methods=['POST'])
    @authenticated()
    @verify_params(submitted='bool')
    def add_to_submit_list(self):
        try:
            data_ids = self.params.get('data_ids')
            if not self.__is_int_array(data_ids):
                return self._render.render_json(code=RESPONSE_PARAMS_ERROR, data=None, msg='data_ids must be int array')
            submitted = self.params.get('submitted')
            controller = TaskController()
            controller.add_to_submit_list(data_ids, submitted)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='提交成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/submit_to_audit', methods=['POST'])
    @authenticated()
    @verify_params(id="int")
    def submit_to_audit(self):
        try:
            task_id = self.params.get('id')
            controller = TaskController()
            controller.submit_to_audit(task_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='提交成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/recall_submit', methods=['POST'])
    @authenticated()
    @verify_params(id="int")
    def recall_submit(self):
        """撤回提交"""
        try:
            task_id = self.params.get('id')
            controller = TaskController()
            controller.recall_submit(task_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='撤回成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/add', methods=['POST'])
    @authenticated()
    @verify_params(task_name='string', batch_id="int")
    def add_task(self):
        """新建任务接口"""
        try:
            task_name = self.params.get('task_name')
            batch_id = self.params.get('batch_id')  # 数据子集id
            user = self.user

            if db.session.query(Task).filter_by(task_name=task_name, batch_id=batch_id).first():
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg="任务名重复了")

            controller = TaskController()
            controller.add_task(user, task_name, batch_id)

            return self._render.render_json(code=RESPONSE_SUCCESS, data={}, msg="新建完成")
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg="系统异常")

    @dispatch('/remove', methods=['POST'])
    @authenticated()
    @verify_params(task_id="int")
    def remove_task(self):
        """删除任务接口"""
        try:
            task_id = self.params.get('task_id')  # 任务id
            # user = self.user

            if not db.session.query(Task).filter_by(task_id=task_id, task_status=TASK_STATUS_NEW).first():
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg="只有新建的任务可删除")

            controller = TaskController()
            controller.remove_task(task_id)

            return self._render.render_json(code=RESPONSE_SUCCESS, data={}, msg="删除完成")
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg="系统异常")

    @dispatch('/get_list', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(page_size='int', page_index='int')
    def get_list(self):
        """任务列表页"""
        try:
            user = self.user
            page_size = self.params.get('page_size')
            page_index = self.params.get('page_index')
            batch_id = self.params.get('batch_id')
            task_status_list = self.params.get('task_status_list')
            if task_status_list is None:
                task_status_list = [constant.TASK_STATUS_NEW, constant.TASK_STATUS_SUBMITTED,
                                    constant.TASK_STATUS_CANCELED, TASK_STATUS_AUDITED,
                                    constant.TASK_STATUS_REJECTED]
            controller = TaskController()
            array, pagination = controller.get_list(user.user_id, page_size, page_index, batch_id, task_status_list)
            data = {'list': array, 'pagination': pagination}
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg="查询成功")
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data={}, msg="系统异常")

    @dispatch('/get_rejected_list', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(page_size='int', page_index='int', data_set_id='int')
    def get_rejected_list(self):
        """任务被驳回列表页"""
        try:
            user = self.user
            page_size = self.params.get('page_size')
            page_index = self.params.get('page_index')
            data_set_id = self.params.get('data_set_id')

            task_status_list = [constant.TASK_STATUS_REJECTED]
            controller = TaskController()
            data = controller.get_list(data_set_id, user.user_id, page_size, page_index, task_status_list)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg="查询成功")
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data={}, msg="系统异常")

    @dispatch('/get_audit_list', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(page_size='int', page_index='int', data_set_id='int')
    def get_audit_list(self):
        """任务审核列表页"""
        try:
            # user = self.user
            page_size = self.params.get('page_size')
            page_index = self.params.get('page_index')
            data_set_id = self.params.get('data_set_id')

            task_status_list = [constant.TASK_STATUS_SUBMITTED,
                                constant.TASK_STATUS_CANCELED, TASK_STATUS_AUDITED]
            controller = TaskController()
            data = controller.get_audit_list(data_set_id, page_size, page_index, task_status_list)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg="查询成功")
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data={}, msg="系统异常")

    """加入通过或者驳回清单中"""

    @dispatch('/data_audit', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(task_id='int', data_list='list', adopt='int')
    def data_audit(self):
        code = RESPONSE_FAILED
        data = {}
        msg = '操作失败'
        try:

            controller = TaskController()
            task_id = self.params.get('task_id')
            data_list = self.params.get('data_list', [])
            remark = self.params.get('remark', '')
            adopt = self.params.get('adopt', '')

            if adopt not in [AUDIT_STATUS_AUDITED, AUDIT_STATUS_REJECTED]:
                return self._render.render_json(code=code, data=data, msg='adopt值错了')

            if controller.data_audit(task_id, data_list, adopt, remark):
                code = RESPONSE_SUCCESS
                msg = '操作成功'
        except:
            writelog(traceback.format_exc())
        return self._render.render_json(code=code, data=data, msg=msg)

    """任务驳回 不通过审核"""

    @dispatch('/task_overruled', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(task_id=int)
    def task_overruled(self):
        code = RESPONSE_FAILED
        msg = '操作失败'
        data = {}
        controller = TaskController()
        task_id = self.params.get('task_id', '')
        remark = self.params.get('remark', '')
        if controller.task_overruled(task_id, remark):
            msg = '操作成功'
            code = RESPONSE_SUCCESS
        return self._render.render_json(code=code, data=data, msg=msg)

    """任务通过审核"""

    @dispatch('/task_adopt', methods=['GET', 'POST'])
    @authenticated()
    @verify_params(task_id=int)
    def task_adopt(self):
        try:
            code = RESPONSE_FAILED
            data = {}
            controller = TaskController()
            task_id = self.params.get('task_id', '')
            success, abnormal_msg = controller.task_adopt(task_id)
            if not success:
                return self._render.render_json(code=code, data=data, msg=abnormal_msg)
            code = RESPONSE_SUCCESS
            return self._render.render_json(code=code, data=data, msg=abnormal_msg)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg="系统异常")

    @dispatch('/delete', methods=['POST'])
    @verify_params(task_id=int)
    @authenticated()
    def delete(self):
        try:
            task_id = self.params.get('task_id')
            controller = TaskController()
            res, msg = controller.delete(task_id)
            if res:
                return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg=msg)
            else:
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg=msg)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/edit', methods=['POST'])
    @verify_params(task_id='int', task_name='string')
    @authenticated()
    def edit(self):
        try:
            task_id = self.params.get('task_id')
            task_name = self.params.get('task_name')
            controller = TaskController()
            controller.edit(task_id, task_name)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='修改成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/add_data_to_task', methods=['POST'])
    @verify_params(task_id=int)
    @authenticated()
    def add_data_to_task(self):
        try:
            task_id = self.params.get('task_id')
            data_ids = self.params.get('data_ids')
            controller = TaskController()
            res, msg = controller.add_data_to_task(task_id, data_ids)
            if res:
                return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='添加成功')
            else:
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg=msg)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/add_all_data_to_task', methods=['POST'])
    @verify_params(task_id=int, batch_id=int)
    @authenticated()
    def add_all_data_to_task(self):
        try:
            task_id = self.params.get('task_id')
            batch_id = self.params.get('batch_id')
            controller = TaskController()
            res, info = controller.add_all_data_to_task(task_id, batch_id)
            if res:
                return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='操作成功')
            else:
                return self._render.render_json(code=RESPONSE_FAILED, data=None, msg=info)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/remove_data_from_task', methods=['POST'])
    @verify_params(relation_id=int)
    @authenticated()
    def remove_data_from_task(self):
        try:
            relation_id = self.params.get('relation_id')
            controller = TaskController()
            controller.remove_data_from_task(relation_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=None, msg='删除成功')
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')

    @dispatch('/get_task_data_relation_count', methods=['GET'])
    @verify_params(task_id=int)
    def get_task_data_relation_count(self):
        try:
            task_id = self.params.get('task_id')
            controller = TaskController()
            count = controller.get_task_data_relation_count(task_id)
            return self._render.render_json(code=RESPONSE_SUCCESS, data=count)
        except:
            writelog(traceback.format_exc())
            return self._render.render_json(code=RESPONSE_FAILED, data=None, msg='系统异常')